<template>
	<view class="container">
		<!-- <view v-if="showHeader" class="status" :style="{position:headerPosition,top:statusTop}"></view>
		<view v-if="showHeader" class="header" :style="{position:headerPosition,top:headerTop}">
			<view class="title">购物车</view>
		</view> -->
		<!-- <view v-if="!hasLogin || empty===true" class="empty">
			<image src="/static/konggouwuche.png" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				<view class="text">暂无商品，快去挑选商品吧！</view>
				<navigator class="navigator" v-if="hasLogin" url="/pages/category/category" open-type="switchTab">去逛逛</navigator>
			</view>
			<view v-else class="empty-tips">
				<view class="text">暂无商品，快去挑选商品吧！</view>
				<view class="navigator" @click="navToLogin">去登陆</view>
			</view>
		</view> -->
		<view v-if="empty===true" class="empty">
			<image src="/static/empty/empty-cart.png" mode="aspectFit"></image>
			<view class="empty-tips">
				<view class="text">暂无商品，快去挑选商品吧！</view>
				<navigator class="navigator" url="/pages/category/category" open-type="switchTab">去逛逛</navigator>
				<!-- <navigator class="navigator" v-if="hasLogin" url="/pages/category/category" open-type="switchTab">去逛逛</navigator> -->
			</view>
			<!-- <view v-else class="empty-tips">
				<view class="text">暂无商品，快去挑选商品吧！</view>
				<view class="navigator" @click="navToLogin">去登陆</view>
			</view> -->
		</view>
		<!-- 商品列表 -->
		<view class="goods-list" v-else>
			<!-- <view class="tis" v-if="cartList.length==0">购物车是空的哦~</view> -->

			<uni-slideview>
				<view class="goods-section" v-for="(item,index) in cartList" :key="index">
					<view class="g-header ellipsis">
						<!-- checkbox -->
						<view class="checkbox-box" @click="selected(index)">
							<view class="checkbox" :class="[ businessSelectFormat(item) ? 'on' : '']"></view>
						</view>
						<!-- 商品信息 -->
						<!-- @tap="toGoods(item.seller_id)" -->
						<view class="text">
							{{item.seller_name}}
						</view>
					</view>

					<view class="row" v-for="(sku,skuIndex) in item.skuList" :key="skuIndex">
						<uni-slideview-item :options="slideviewOptions" @click="slideClick($event, index, sku.sku_id)">
							<view class="checkbox-box" @click.stop="selectedItem(index, skuIndex)">
								<view class="checkbox" :class="[singleSelectFormat(sku) ? 'on' : '']"></view>
							</view>
							<!-- 商品信息 -->
							<view class="goods-info" @tap.stop="toGoods(sku)">
								<view class="img">
									<image :src="imgsrc + sku.pic"></image>
								</view>
								<view class="info">
									<view class="title">{{sku.product_name}}</view>
									<view class="spec">{{sku.detail_desc}}</view>
									<view class="price-number">
										<view class="price">
											<text>￥</text>
											<text class="num-font">{{sku.price}}</text>
										</view>
										<view class="number">
											<view class="sub" @tap.stop="sub(index,skuIndex)">
												<view class="yticon icon--jianhao"></view>
											</view>
											<view class="input num-font">
												<input type="number" v-model="sku.count" @blur.stop="numberChange($event,index,skuIndex)" />
											</view>
											<view class="add" @tap.stop="add(index,skuIndex)">
												<view class="yticon icon-jia2"></view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</uni-slideview-item>
					</view>
				</view>

			</uni-slideview>
			<!-- 脚部菜单 -->
			<view class="footer" v-if="cartList.length > 0" :style="{bottom:footerbottom}">
				<view class="checkbox-box" @tap="allSelect">
					<view class="checkbox" :class="[ allSelectFormat ? 'on' : '' ]"></view>
				</view>
				<view class="text">全选</view>
				<view class="delBtn" @tap="deleteList" v-if="selectedList.length > 0">删除</view>

				<view class="settlement">
					<view class="sum">
						<text>合计:</text>
						<view class="money">
							<text>￥</text>
							<text class="num-font">{{moneyFormat}}</text>
						</view>
					</view>
					<view class="btn num-font" @tap="toConfirmation">结算({{selectedList.length}})</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import Api from '@/common/api';
	import uniSlideview from '@/components/uni-swipe-action/uni-swipe-action.vue';
	import uniSlideviewItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'
	
	export default {
		components: {
			uniSlideview,
			uniSlideviewItem
		},
		data() {
			return {
				imgsrc: Api.imgsrc,
				empty: false, //空白页现实  true|false
				sumPrice: '0.00',
				selectedList: [],
				isAllselected: false,
				// total_count: null,
				slideStatus: false,
				cartList: [],
				footerbottom: 0,
				slideviewOptions: [{
						text: '移入收藏',
						style: {
							backgroundImage: `linear-gradient(to bottom , #ffc000, #ffe26a)`
						}
					},
					{
						text: '删除',
						style: {
							backgroundImage: `linear-gradient(to bottom , #FF0000, #ff5c5c)`
						}
					}
				]
			}
		},
		onPageScroll(e) {
			//兼容iOS端下拉时顶部漂移
			// this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
			// this.headerTop = e.scrollTop >= 0 ? null : 0;
			// this.statusTop = e.scrollTop >= 0 ? null : -this.statusHeight + 'px';
		},
		//下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onShow(option) {
			//兼容H5下结算条位置
			// #ifdef H5
			this.footerbottom = document.getElementsByTagName('uni-tabbar')[0].offsetHeight + 'px';
			// #endif
			// #ifdef APP-PLUS
			this.showHeader = false;
			// this.statusHeight = plus.navigator.getStatusbarHeight();
			// #endif
			uni.$once('deleteSeleted', e => {
				if (this.selectedList.length > 0) this.deleteList(); //创建订单成功并跳转成功同时删除选定的购物车商品
			})
			this.loadData();
		},
		watch: {
			//显示空白页
			cartList(newVal) {
				let empty = newVal.length == 0;
				if (this.empty !== empty) {
					this.empty = empty;
				}
				let skuListLength = newVal.reduce((prev, cur) => prev + cur.skuList.length , 0)
				if(skuListLength > 0){
					uni.setTabBarBadge({
					  index: 2,
					  text: `${skuListLength}`
					})
				}else{
					uni.removeTabBarBadge({
						index: 2
					})
				}
			}
		},
		computed: {
			...mapState(['hasLogin']),
			moneyFormat() {
				let num = 0;
				this.cartList.forEach(cartItem => {
					cartItem.skuList.forEach(skuItem => {
						if (this.selectedList.includes(skuItem.sku_id)) {
							num = num + (skuItem.count * skuItem.price);
						}
					});
				});
				return parseFloat(num).toFixed(2);
			},
			allSelectFormat() {
				return this.selectedList.length == this.cartList.reduce((prev, cur) => {
					return prev + cur.skuList.length
				}, 0);
			},
			businessSelectFormat() {
				return (item) => {
					return item.skuList.every(e => {
						return this.selectedList.includes(e.sku_id)
					})
				}
			},
			singleSelectFormat() {
				return (sku) => {
					return this.selectedList.includes(sku.sku_id);
				}
			}
		},
		methods: {
			//请求数据
			async loadData() {
				let params = {},
					method = 'POST',
					data;
				// 用户未登录状态时
				if (!this.hasLogin) {
					let cartList = uni.getStorageSync('cartList');
					
					if (cartList) {
						params = {
							'skuList': cartList
						};
						method = 'GET';
					} else {
						this.cartList = [];
						return;
					}
				}
				data = await Api.apiCall(method, Api.order.cartList, params);
				if (data) {
					this.selectedList = [];
					this.cartList = data.cartList.map(cartItem => {
						cartItem.skuList.map(skuItem => {
							skuItem.count = Number(skuItem.count)
							return skuItem
						});
						return cartItem;
					});
				}
			},
			//商品跳转
			toGoods(e) {
				uni.navigateTo({
					url: `/mall/product/product?product_id=${e.product_id}&navigateFrom=cart`
				});
			},
			//跳转确认订单页面
			toConfirmation() {
				let cartList = [];
				if (!this.hasLogin) {
					uni.navigateTo({
						url: '/pages/public/login'
					})
					return;
				}
				if (this.selectedList.length == 0) {
					uni.showToast({
						icon: "none",
						title: '您还没有选择商品哦'
					})
					return;
				};
				this.cartList.forEach(cartItem => {
					cartItem.skuList.forEach(skuItem => {
						let skuList = [];
						if (this.selectedList.includes(skuItem.sku_id)) {
							skuList.push({
								"sku": skuItem.sku_id,
								"qty": skuItem.count
							})
							let findIndex = cartList.findIndex(e => cartItem.seller_id == e.sellerid);
							if (findIndex != -1) {
								cartList[findIndex].skus = cartList[findIndex].skus.concat(skuList)
							} else {
								cartList.push({
									"sellerid": cartItem.seller_id,
									"skus": skuList
								});
							}



						}
					});

				})
				console.log(cartList);
				uni.setStorage({
					key: 'buylist',
					data: cartList,
					success: () => {
						uni.navigateTo({
							url: '/mall/order/createOrder'
						})
					}
				})
			},

			slideClick(e, index, skuId) {
				switch (e.index) {
					case 0: //收藏
						uni.showToast({
							icon: "none",
							title: "收藏暂未开启"
						})
						break;
					case 1: //删除
						this.deleteGoods(index, skuId);
						break;
				}
			},

			//删除一个商品
			async deleteGoods(index, skuId) {
				let skuList = this.cartList[index].skuList
				//清除页面显示的商品sku
				skuList.splice(skuList.findIndex(e => e.sku_id == skuId), 1);
				if (this.selectedList.indexOf(skuId) != -1) this.selectedList.splice(this.selectedList.indexOf(skuId), 1);
				//如果对应的cartList为空，则删除商家信息
				if (skuList.length == 0) this.cartList.splice(index, 1);

				// 用户未登录状态时
				if (!this.hasLogin) {
					let cartList = uni.getStorageSync('cartList')
					if (cartList) {
						//清除缓存的商品sku
						cartList.splice(cartList.findIndex(e => e.sku_id == skuId), 1)
						uni.setStorageSync('cartList', cartList);
					}
				} else {
					let params = {
							'sku_id': skuId
						},
						method = 'DELETE',
						data = await Api.apiCall(method, Api.order.Cart, params);
				}


			},
			// 删除多个商品
			deleteList() {
				while (this.deleteCheck()) {
					let index, skuId;
					let isExistence = this.cartList.some((cartItem, cartIndex) => {
						return cartItem.skuList.some(skuItem => {
							if (this.selectedList.includes(skuItem.sku_id)) {
								index = cartIndex;
								skuId = skuItem.sku_id
							}
							return this.selectedList.includes(skuItem.sku_id)
						})
					})
					this.deleteGoods(index, skuId);
				}
			},
			deleteCheck() {
				return this.cartList.some((cartItem, index) => {
					return cartItem.skuList.some(skuItem => {
						return this.selectedList.includes(skuItem.sku_id)
					})
				})
			},

			// 选择商家
			selected(index) {
				let skuList = this.cartList[index].skuList;
				let selected = skuList.length != this.selectedList.reduce((prev, cur) => {
					return prev + (skuList.some(e => e.sku_id == cur) ? 1 : 0)
				}, 0)
				skuList.forEach(skuItem => {
					if (this.selectedList.includes(skuItem.sku_id)) {
						let findIndex = this.selectedList.indexOf(skuItem.sku_id);
						this.selectedList.splice(findIndex, 1);
					}
				});
				if (selected) {
					skuList.forEach(skuItem => {
						this.selectedList.push(skuItem.sku_id)
					})
				}
			},

			//选择单个商品
			selectedItem(index, skuIndex) {
				let skuId = this.cartList[index].skuList[skuIndex].sku_id;
				let findIndex = this.selectedList.indexOf(skuId);
				findIndex != -1 ? this.selectedList.splice(findIndex, 1) : this.selectedList.push(skuId);
			},

			//全选
			allSelect() {
				let allSelect = this.selectedList.length != this.cartList.reduce((prev, cur) => {
					return prev + cur.skuList.length
				}, 0);
				this.selectedList = [];
				if (allSelect) {
					this.cartList.forEach(cartItem => {
						cartItem.skuList.forEach(skuItem => {
							this.selectedList.push(skuItem.sku_id);
						});
					});
				}
			},

			// 减少数量
			async sub(index, skuIndex) {
				let count = this.cartList[index].skuList[skuIndex].count;
				if (count <= 1) {
					uni.showToast({
						icon: "none",
						title: '最少购买一件哦！'
					})
					return;
				};
				this.cartList[index].skuList[skuIndex].count--;
				if (this.hasLogin) {
					let params = {
						'sku_list': [{
							"sku_id": this.cartList[index].skuList[skuIndex].sku_id,
							"count": this.cartList[index].skuList[skuIndex].count
						}]
					};

					let data = await Api.apiCall('put', Api.order.Cart, params, true);
				} else {
					let cartList = uni.getStorageSync('cartList');
					if (cartList) {
						cartList.forEach(item => {
							if (item.sku_id == this.cartList[index].skuList[skuIndex].sku_id) {
								item.count = this.cartList[index].skuList[skuIndex].count;
							}
						})
						uni.setStorageSync('cartList', cartList);
					}
				}
			},

			// 增加数量
			async add(index, skuIndex) {
				let count = this.cartList[index].skuList[skuIndex].count;
				if (count > 200) {
					uni.showToast({
						title: '最多只能买200件哦!',
						icon: 'none'
					});
					return;
				}
				this.cartList[index].skuList[skuIndex].count++;
				if (this.hasLogin) {
					let params = {
						'sku_list': [{
							"sku_id": this.cartList[index].skuList[skuIndex].sku_id,
							"count": this.cartList[index].skuList[skuIndex].count
						}]
					};
					let data = await Api.apiCall('put', Api.order.Cart, params, true);
				} else {
					let cart_list = uni.getStorageSync('cartList');
					if (cart_list) {
						cart_list.forEach(item => {
							if (item.sku_id === this.cartList[index].skuList[skuIndex].sku_id) {
								item.count = this.cartList[index].skuList[skuIndex].count;
							}
						})
						uni.setStorageSync('cartList', cart_list);
					}
				}
			},

			// 修改文本框
			async numberChange(event, index, skuIndex) {
				let count = event.detail.value;
				console.log('***', count)
				if (!count || count < 1 || count > 200) {
					this.inputValue = 1;
					return
				}
				if (this.hasLogin) {
					let params = {
						'sku_id': this.cartList[index].skuList[skuIndex].sku_id,
						'count': count
					};

					let data = await Api.apiCall('put', Api.order.Cart, params);
				} else {
					let cartList = uni.getStorageSync('cartList');
					if (cartList) {
						cartList.forEach(item => {
							if (item.sku_id === this.cartList[index].skuList[skuIndex].sku_id) {
								item.count = parseInt(count);
							}
						})
						uni.setStorageSync('cartList', cartList);
					}
				}
			},
			navToLogin() {
				uni.navigateTo({
					url: '/pages/public/login'
				})
			}
		}
	}
</script>
<style lang="scss">
	page {
		position: relative;
		background-color: #FAFAFA;
	}

	.container {
		/* padding-bottom: 134upx; */
		width: 100%;
		-webkit-overflow-scrolling: touch;

		/* 空白页 */
		.empty {
			position: fixed;
			left: 0;
			top: 88upx;
			width: 100%;
			padding-top: 189upx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;

			image {
				width: 270upx;
				height: 318upx;
				margin-bottom: 30upx;
			}

			.empty-tips {
				.text {
					width: 100%;
					height: 40upx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24upx;
					color: #ABADAD;
				}

				.navigator {
					width: 250upx;
					height: 88upx;
					display: flex;
					margin-top: 61upx;
					margin-left: 30upx;
					align-items: center;
					justify-content: center;
					border-radius: 44upx;
					color: #232323;
					font-size: 28upx;
					background-color: #FFBC21;
				}
			}
		}
	}

	.checkbox-box {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-shrink: 0;
		height: 100%;
		width: 100upx;
		// margin-left: 30upx;

		.checkbox {
			width: 40upx;
			height: 40upx;
			position: relative;
			border-radius: 50%;
			border: 4upx solid #ababab;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			overflow: hidden;

			&.on {
				background-color: #FFBC21;
				border-color: #FFBC21;
				box-shadow: 0 3upx 8upx #FFBC21;

				&::before {
					font: normal normal normal 14px/1 uni;
					content: "\EA08";
					color: #fff;
					font-size: 18px;
					transform: scale(.6);
				}
			}
		}

		.text {
			font-size: 28upx;
			margin-left: 10upx;
		}
	}

	.status {
		width: 100%;
		height: 0;
		position: fixed;
		z-index: 10;
		background-color: #fff;
		top: 0;
		/*  #ifdef  APP-PLUS  */
		height: var(--status-bar-height); //覆盖样式
		/*  #endif  */
	}

	// .header {
	// 	width: 100%;
	// 	padding: 0 4%;
	// 	height: 100upx;
	// 	display: flex;
	// 	align-items: center;
	// 	position: fixed;
	// 	top: 0;
	// 	z-index: 10;
	// 	background-color: #fff;
	// 	border-bottom: 1px solid $border-color-base;
	// 	/*  #ifdef  APP-PLUS  */
	// 	top: var(--status-bar-height);

	// 	/*  #endif  */
	// 	.title {
	// 		font-size: 36upx;
	// 	}

	// }

	.goods-list {
		width: 100%;
		margin-top: 10upx;
		padding-bottom: 120upx;
		position: relative;
		z-index: 1;
		// .tis {
		// 	width: 100%;
		// 	height: 60upx;
		// 	display: flex;
		// 	justify-content: center;
		// 	align-items: center;
		// 	font-size: 32upx;
		// }

		.goods-section {
			width: 100%;
			margin-bottom: 30upx;
			background-color: #fff;
			box-sizing: border-box;
			border-radius: 20upx;

			.g-header {
				position: sticky;
				top: 0;
				display: flex;
				align-items: center;
				width: 100%;
				height: 88upx;
				color: #232323;
				font-size: 30upx;
				box-sizing: border-box;
				padding-right: 30upx;
				background-color: #FFF;
				z-index: 5;

				.text {
					width: 100%;
					// padding-left: 30upx;
				}
			}

			.row {
				width: 100%;
				height: 270upx;
				padding: 20upx auto;
				display: flex;
				align-items: center;
				position: relative;
				overflow: hidden;
				z-index: 4;
				border: 0;

				&::before {
					content: '';
					position: absolute;
					bottom: 0;
					right: 0;
					height: 2upx;
					width: calc(100vw - 30upx);
					background-color: rgba(234, 234, 234, 1);
				}

				&:last-child::before {
					content: unset;
				}

				.goods-info {
					width: 100%;
					display: flex;
					padding: 10upx 30upx 20upx 0;
					z-index: 3;

					.img {
						width: 209upx;
						height: 209upx;
						margin-right: 30upx;
						border-radius: 10upx;
						overflow: hidden;
						flex-shrink: 0;

						image {
							width: 209upx;
							height: 209upx;
						}
					}

					.info {
						width: 100%;
						height: 209upx;
						overflow: hidden;
						display: flex;
						flex-wrap: wrap;
						position: relative;

						.title {
							width: 100%;
							font-size: 28upx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							color: #232323;
							// text-align: justify;
							overflow: hidden;
						}

						.spec {
							font-size: 24upx;
							// background-color: #f3f3f3;
							color: #a7a7a7;
							height: 30upx;
							display: flex;
							align-items: center;
							border-radius: 15upx;
							margin-bottom: 54upx;
						}

						.price-number {
							position: absolute;
							width: 100%;
							bottom: 0upx;
							display: flex;
							justify-content: space-between;
							align-items: flex-end;
							font-size: 28upx;
							height: 60upx;

							.price {
								font-size: 36upx;
								color: #232323;

								text {
									&:first-child {
										font-size: 24upx;
									}
								}
							}

							.number {
								// width: 192upx;
								// height: 58upx;
								display: flex;
								justify-content: center;
								align-items: flex-end;
								background-color: #ffffff;

								.input {
									width: 64upx;
									height: 64upx;
									border-top: .5upx solid #EAEAEA;
									border-bottom: .5upx solid #EAEAEA;

									input {
										width: 64upx;
										height: 64upx;
										display: flex;
										justify-content: center;
										align-items: center;
										text-align: center;
										font-size: 26upx;
									}
								}

								.sub,
								.add {
									width: 64upx;
									height: 64upx;
									border: .5upx solid #EAEAEA;


									.yticon {
										font-size: 22upx;
										width: 64upx;
										height: 64upx;
										display: flex;
										justify-content: center;
										align-items: center;

									}
								}

								.sub {
									border-radius: 5upx 0 0 5upx;
								}

								.add {
									border-radius: 0 5upx 5upx 0;
								}
							}
						}
					}
				}

			}


		}

	}

	.footer {
		width: 100%;
		padding-right: 30upx;
		background-color: #f7f7f7;
		height: 100upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 28upx;
		position: fixed;
		bottom: 0upx;
		z-index: 5;
		border-top: .5upx solid #F1F1F1;

		.delBtn {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 70upx;
			padding: 0 25upx;
			font-size: 28upx;
			border-radius: 35upx;
			border: .5upx solid #232323;
			box-sizing: border-box;
			color: #232323;
			margin-left: 30upx;


			// border: solid 1upx #f06c7a;
			// color: #f06c7a;
			// padding: 0 30upx;
			// height: 50upx;
			// border-radius: 30upx;
		}

		.settlement {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.sum {
				font-size: 28upx;
				margin-right: 10upx;
				display: flex;
				justify-content: flex-end;

				.money {
					color: #E52631;
					font-weight: 600;

					text {
						&:first-child {
							font-size: 24upx;
						}
					}
				}
			}

			.btn {
				height: 78upx;
				padding: 0 20upx;
				background-color: #FFBC21;
				color: #232323;
				font-size: 28upx;
				display: flex;
				justify-content: center;
				align-items: center;

				border-radius: 39upx;
			}
		}
	}
</style>
